import axios from 'axios'
import store from '@/store'
import { Toast, Dialog } from 'vant'
import { getToken, removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  baseURL: 'http://gem.com/api/v1/',
  // baseURL: 'http://gemback.12806.cn/api/v1/',
  timeout: 5000 // request timeout
})

// request拦截器
service.interceptors.request.use(
  config => {
    var loginToekn = getToken()
    /* if (store.getters.token)
    {
      config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    } */
    if (loginToekn) {
      config.headers['x-api-key'] = loginToekn // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response.status === 401) {
      removeToken()
      Dialog.alert({
        message: '登录已过期，请重新登录!',
        theme: 'round-button'
      }).then(() => {
        location.reload()
      })
      /* Toast.confirm(
        '登录已过期，请重新登录',
        {
          showCancelButton: false,
          showClose: false,
          closeOnPressEscape: false,
          closeOnClickModal: false,
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() =>
      {
        removeToken()
        location.reload()   }) */
    } else {
      Toast(error.response.data.message)
      /* Message({
        message: error.response.data.message,
        type: 'error',
        duration: 5 * 1000
      }) */
    }
    return Promise.reject(error.response)
  }
)

export default service
